<!--
/**
* Author: txj
* Date: 2023年8月15日15:53:10 
* Desc: 点餐下单页
*/
-->
<template>
  <view class="main">
    <view class="flex-1 scorll">
      <view class="pd30 bc-white">
        <view class="fs30 fc3 b">取餐影城</view>
        <view class="mt35 flex-b">
          <view class="fs30 fc3">{{ cinemaInfo.cinemaName }}</view>
          <view>{{ getDistance() }}</view>
        </view>
        <view class="fs24 fc9 mt20">{{ cinemaInfo.address }}</view>
      </view>
      <view class="pd30 bc-white mt20">
        <!-- <view class="flex-b">
          <view class="fs30 fc3 b">取餐码</view>
          <view class="">
            <view class="fs36 fc-yellow b">888888</view>
            <view class="fs24 fc3 mt15">出餐中</view>
          </view>
        </view> -->
        <view class="flex-b flex-m">
          <view class="fs30 fc3 b">取餐时间</view>
          <view class="flex" @click="openPickTime">
            <view class="fs24 fc3 mr5">{{ pickTime.name }}</view>
            <u-icon name="arrow-right" color="#333" size="12"></u-icon>
          </view>
        </view>
      </view>
      <view class="pd30 bc-white mt20">
        <view class="fs30 fc3 b mb20">点餐明细</view>
        <mall-buy-item-by-sure-order
          no-delete
          v-for="(item, i) in listData"
          :key="i"
          :item-data="item"
          v-model="item.num"
        >
        </mall-buy-item-by-sure-order>
      </view>
      <view
        v-if="list.length > 0"
        class="over-hide mt15 bgfff"
        @click="useCard"
      >
        <u-cell is-link>
          <view slot="title">
            <view class="mb20 fs30">会员卡</view>
            <view class="fc-yellow" v-if="card">-￥{{ totalPrice }}</view>
            <view v-else class="fs24">请选择会员卡</view>
          </view>
        </u-cell>
      </view>
    </view>
    <order-info-footer
      v-model="showMore"
      :ext-pay-class="extPayClass"
      :list="getList()"
      :get-need-price="getPrice"
      @showMore="showMore = !showMore"
      @goPay="getTmplIds"
    ></order-info-footer>
    <mall-pick-time
      v-if="showPickTime"
      v-model="showPickTime"
      @setPickTime="setPickTime"
      :list="timeList"
    ></mall-pick-time>
  </view>
</template>

<script>
  import MallBuyItemBySureOrder from './mallBuyItemBySureOrder.vue'
  import MallPickTime from './mallPickTime.vue'
  import { locSelmallData, locSelCard } from '@/utils/locStore/data'
  import { mapGetters } from 'vuex'
  import OrderInfoFooter from '@/components/OrderInfoFooter'
  export default {
    // 挂载组件
    components: {
      MallBuyItemBySureOrder,
      MallPickTime,
      OrderInfoFooter
    },

    // 数据
    data() {
      return {
        listData: [],
        list: [],
        timeList: [],
        pickTime: {},
        card: null,
        showPickTime: false,
        showMore: false
      }
    },
    onShow() {
      this.card = locSelCard.get() || null
    },
    // 计算属性
    computed: {
      ...mapGetters(['cinemaInfo']),
      totalPrice() {
        let price = 0
        this.listData.forEach((item) => {
          if (!item.coupons || item.coupons.length === 0) {
            price += item.num * item.salePrice
          }
        })
        return price
      },
      getPrice() {
        let price = this.totalPrice
        if (this.card) {
          price = 0
        }
        return price
      }
    },

    // 挂载完成
    mounted() {},

    // 创建完成
    created() {},
    onLoad() {
      this.listData = locSelmallData.get() || []
      console.log('onLoad', this.listData)
      locSelCard.remove() //清空选卡数据
      this.getFoodTimeTypeList()
      this.getCardNum()
    },
    watch: {
      totalPrice: {
        handler() {
          if (this.card && this.totalPrice > this.card.balance) {
            this.card = null
          }
        },
        immediate: true
      }
    },
    // 挂载方法
    methods: {
      getCart() {
        const shoppingCart = []
        console.log('listData', this.listData)
        this.listData.forEach((item) => {
          const mall = {
            merchandiseId: item.merchandiseId,
            number: item.num,
            classificationId: item.classificationId
          }
          if (item.coupons && item.coupons.length > 0) {
            mall.useCode = item.coupons.join()
            mall.number = item.coupons.length
          }
          shoppingCart.push(mall)
        })
        return shoppingCart
      },
      getCardNum() {
        if (this.$auth.memberSystemStatus() === '1') {
          const shoppingCart = this.getCart()
          console.log('shoppingCart', shoppingCart)
          uni.$api.memberCard
            .getMemberCardByFoodCart({
              shoppingCart: JSON.stringify(shoppingCart),
              cinemaId: this.$auth.getLocCinemaInfo().cinemaId
            })
            .then((res) => {
              this.list = res.list
            })
        }
      },
      getDistance() {
        const { lat, lng } = this.$auth.getLoctionAreaInfo()

        const distance = this.$utils.getDistance(
          lat,
          lng,
          this.cinemaInfo.latitude,
          this.cinemaInfo.longitude
        ) // 计算距离
        return this.$utils.getDistanceTxt(distance)
      },
      getFoodTimeTypeList() {
        uni.$api.orderFood.getFoodTimeTypeList().then((res) => {
          this.timeList = res
          if (res.length > 0) {
            this.pickTime = this.timeList[0]
          }
        })
      },
      getTmplIds() {
        // #ifndef MP-WEIXIN
        this.toPay()
        // #endif
        // #ifdef MP-WEIXIN
        uni.$api.orderFood.getTemplateOfOrderCompletedMsg().then((res) => {
          const tmplIds = res.map((item) => item.priTmplId)
          wx.getSetting({
            withSubscriptions: true,
            success: (res) => {
              console.log(res, 'set-res')
              if (res.subscriptionsSetting) {
                const { mainSwitch = true, itemSettings = {} } =
                  res.subscriptionsSetting
                if (mainSwitch) {
                  wx.requestSubscribeMessage({
                    tmplIds,
                    success: (res) => {
                      this.toPay()
                      console.log(res, 'sub-res')
                    },
                    fail: (err) => {
                      this.toPay()
                      console.log(err, 'sub-err')
                    }
                  })
                } else {
                  this.toPay()
                }
              }
            },
            fail: (err) => {
              this.toPay()
              console.log(err, 'set-err')
            }
          })
        })
        // #endif
      },
      toPay() {
        const shoppingCart = []
        console.log('listData', this.listData)
        this.listData.forEach((item) => {
          const mall = {
            merchandiseId: item.merchandiseId,
            number: item.num,
            classificationId: item.classificationId
          }
          if (item.coupons && item.coupons.length > 0) {
            mall.useCode = item.coupons.join()
            mall.number = item.coupons.length
          }
          shoppingCart.push(mall)
        })
        console.log('shoppingCart', shoppingCart)
        uni.$api.orderFood
          .createOrder({
            shoppingCart: JSON.stringify(shoppingCart),
            getFoodTimeType: this.pickTime.value,
            cardId: this.card ? this.card.id : '',
            cinemaId: this.$auth.getLocCinemaInfo().cinemaId
          })
          .then((res) => {
            const resData = res
            const query = {
              foodOrderId: resData.orderId,
              cardId: this.card ? this.card.id : '',
              orderType: 'food',
              needPay: this.getPrice
            }
            this.$tools.navigateTo('/pagesOrder/pay/index', query)
          })
          .catch((res) => {
            console.log('catch', res)
            if (res && res.data && res.data.status === '60010') {
              this.$tools.navigateTo(-1)
              uni.setStorageSync('reDataMallBuy', res.data.content)
            }
          })
      },
      openPickTime() {
        this.showPickTime = true
      },
      setPickTime(time) {
        const shoppingCart = []
        this.listData.forEach((item) => {
          const mall = {
            merchandiseId: item.merchandiseId,
            number: item.num,
            classificationId: item.classificationId
          }
          shoppingCart.push(mall)
        })
        console.log('setPickTime', time)
        uni.$api.orderFood
          .checkFoodTime({
            getFoodTimeType: time.value,
            shoppingCart: JSON.stringify(shoppingCart),
            cinemaId: this.$auth.getLocCinemaInfo().cinemaId
          })
          .then((res) => {
            if (res.isTip) {
              this.$msg
                .showModal({
                  title: '取餐时间提醒',
                  content: res.tipMessage,
                  cancelText: '修改时间',
                  confirmText: '仍然确定'
                })
                .then(() => {
                  this.pickTime = time
                })
            } else {
              this.pickTime = time
            }
          })
      },
      useCard() {
        const shoppingCart = this.getCart()
        const query = this.$utils.encode(shoppingCart)

        // this.$tools.navigateTo('/pagesOrder/card/index', {
        //   fromPage: 'mallPay',
        //   totalPrice: this.getPrice,
        //   cinemaId: this.$auth.getLocCinemaInfo().cinemaId,
        //   shoppingCart: this.$utils.encode(shoppingCart)
        // })
        this.$tools.navigateTo(
          `/pagesOrder/card/index?shoppingCart=${query}&&totalPrice=${
            this.getPrice
          }&&cinemaId=${
            this.$auth.getLocCinemaInfo().cinemaId
          }&&fromPage=mallPay`
        )
      },
      getList() {
        const list = []

        this.listData.forEach((item) => {
          list.push({
            name: item.name,
            value: '￥' + item.salePrice * item.num,
            type: '0',
            useCoupon: item.coupons && item.coupons.length > 0
          })
        })
        let money = 0
        console.log('card', this.card)
        if (this.card) {
          money = this.totalPrice
        }
        money &&
          list.push({
            name: '会员卡支付',
            value: '-￥' + money,
            type: '0'
          })
        return list
      }
    }
  }
</script>
<style lang="scss" scoped>
  .main {
    background-color: #f2f2f2;
    height: calc(100vh - 200rpx);
    padding-bottom: 200rpx;
    flex-direction: column;
    display: flex;
    .scorll {
      overflow: scroll;
    }

    .buttom-view {
      background-color: white;
      height: 140rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      box-sizing: border-box;
      padding: 20rpx 30rpx;
      .btn {
        width: 246rpx;
        height: 100rpx;
        color: white;
        font-size: 36rpx;
        background: linear-gradient(135deg, #55baff 0%, #23e6d8 100%);
        border-radius: 18rpx;
        text-align: center;
        line-height: 100rpx;
      }
    }
  }
</style>
